import { defineConfig, BuildOptions } from "vite";
import vue from "@vitejs/plugin-vue";
import { resolve } from "path";
import Delete from "rollup-plugin-delete";
import dts from "./plugins/dts";
import { createPlugin, vueDocFiles } from "vite-plugin-vuedoc";
import markdownItContainer from "markdown-it-container";

const containers = ["success", "warning", "info", "error"].map((type) => {
  return [
    markdownItContainer,
    type,
    {
      validate: function (params: string) {
        const str = params.trim();
        if (str === type || str.startsWith(`${type} `)) {
          return [str, str === type ? "" : str.substr(type.length + 1)];
        }
        return null;
      },
      render: function (tokens: any[], idx: number) {
        const str = tokens[idx].info.trim();
        const m = [str, str === type ? "" : str.substr(type.length + 1)];
        if (tokens[idx].nesting === 1) {
          // opening tag
          return `<p><e-alert type="${type}" :closable="false" title="${m[1]}" >`;
        } else {
          // closing tag
          return "</e-alert></p>";
        }
      },
    },
  ];
});

const bundlingConf: BuildOptions = {
  lib: {
    entry: resolve(__dirname, "./src/m-ui/index.ts"),
    name: "MUI",
    formats: ["es", "umd", "cjs"],
  },

  rollupOptions: {
    plugins: [
      // Rollup generates all the files, then remove what we don't want.
      // @todo: find a better way.
      Delete({
        targets: ["dist/{images,.htaccess,ghspa.js}", "dist/*.{ico,txt,html}"],
        hook: "generateBundle",
      }),
    ],
    // Make sure to externalize deps that shouldn't be bundled into library.
    external: ["vue"],
    output: {
      // Provide global variables to use in the UMD build for externalized deps.
      globals: { vue: "Vue" },
    },
  },
};

const build = process.env.BUNDLE ? bundlingConf : { outDir: "docs" };
const plugins = process.env.BUNDLE
  ? [
      vue({
        template: {
          compilerOptions: {
            whitespace: "preserve",
          },
        },
      }),
      dts(),
    ]
  : [
      createPlugin({
        markdownIt: {
          plugins: [...containers],
        },
        highlight: {
          theme: "one-dark",
        },
      }),
      vue({
        include: [...vueDocFiles],
        // template: {
        //   compilerOptions: {
        //     whitespace: "preserve",
        //   },
        // },
      }),
    ];
export default defineConfig({
  define: {
    "process.env": {
      // ...process.env,
      // VITE_APP_VERSION: process.env.npm_package_version,
    },
  },
  plugins, // https://vitejs.dev/config/
  css: {
    preprocessorOptions: {
      scss: {
        // additionalData:
        //   '@import "/@/m-ui/scss/common/var";@import "/@/m-ui/scss/mixins/mixin";',
      },
    },
  },
  resolve: {
    alias: {
      "/@": resolve(__dirname, "./src"),
    },
  },
  build,
});
